# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.http import HttpResponseRedirect

from django.db import connection
from django.template.loader import get_template
from django.template import Context
from django.template import RequestContext

from django.shortcuts import render_to_response

from django.core.context_processors import csrf

from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

from django.contrib import auth

from pyofc2  import *

#import pyexpat
#import SOAPpy
from SOAPpy import WSDL
import os

import datetime
import random
import time

import math
import urllib
from stocktable import stocklist

import scriptt

def cacltest1(request):
    c=scriptt.ScriptEngine()
    s= c.run()
    return HttpResponse(str(len(s)) + " " + str(s))
    
def cacltest2(request):
    c=scriptt.ScriptEngine()
    s = c.run4()
    
    return HttpResponse(str(s['b'].data) + " " + str(s['c'].data) )

def cacltest3(request):
    c=scriptt.ScriptEngine()
    return HttpResponse(str(c.run3().v))

def urldecode(query):
    d = {}
    a = query.split('&')
    for s in a:
        if s.find('='):
            k,v = map(urllib.unquote, s.split('='))
            try:
                d[k].append(v)
            except KeyError:
                d[k] = [v]
    return d


class DEAL_INFO:
    stock_id=""
    datetime=""
    num_deals=0
    num_transactions = 0
    deal_type = 0
    price = 0.0
    
    def __str__(self):
        return self.stock_id + " " + str(self.num_deals) + " "+ str(self.num_transactions) + " " + str(self.deal_type) + " " + str(self.price) + " " + self.datetime

class STOCK_INFO:
    stock_id = ""
    stock_name = ""


def fetch_all_stock_info_from_file(name_startWith, max_row, name_startWithZh):
    #cursor = connection.cursor()
    #cursor.execute("select STOCK_ID, STOCK_NAME from STOCK_INFO")
    li = []
    
    row = range(0, len(stocklist))
    for i in row:
        stock = STOCK_INFO()
        stock.stock_id = stocklist[i][0]
        stock.stock_name = stocklist[i][1]

        if stock.stock_id.startswith(name_startWith) or stock.stock_name.startswith(name_startWithZh):
            li.append(stock)

        if len(li) >= max_row:
            break
        
    return li
    
def fetch_all_stock_info(request):
    if request.method == "GET":
        url = request.get_full_path()
        
        param = request.GET['callback']
        max_row = int(request.GET['maxRows'])
        name_startWith="#"
        name_startWithZh = "#"
        
        try:
            name_startWith = str(request.GET['name_startsWith'])
        except:
            url=url.encode('utf-8')
            name_startWithZh = urldecode(url)["name_startsWith"][0]
            print "error"
        #return HttpResponse(url + " " + name_startWithZh)
        #return HttpResponse(name_startWithZh)
        json_data = ""
           
        #li = ['"000510-金路集团"', '"000561-烽火电子"', '"000637-茂化实华"', '"000720-ST能山"', '"000720-江淮动力"', '"002336-人人乐"']
        li = []

        stock_list = fetch_all_stock_info_from_file(name_startWith, max_row, name_startWithZh)
        
        for stock in stock_list:
            li.append('"'+stock.stock_id + " " + stock.stock_name+'"')

        json_data = "{"
        #json_data += 'totalResultsCount' + ":" + str(len(li)) + ","

        json_data += 'stocknames' + ":"
        json_data += "["

        if li:
            json_data += li[0]
            for i in li[1:len(li)]:
                json_data += ","
                json_data += i
        
        json_data += "]"
        json_data += "}"
        
        return HttpResponse(json_data)
    
def fetch_stock_deal_info(request):
    if request.method=="POST":
        param=request.POST['searchid']
        if param.find(' ') >= 0:
            param = param.split(' ')[0]

        if int(param) >= 600000:
            tag = "sh"
        else:
            tag = "sz"
        
        if not request.user.is_authenticated():
            return render_to_response("stock_main.html", {"stockid":param, "tag":tag},context_instance=RequestContext(request))
        else:
            return render_to_response("stock_main.html", {"stockid":param, "tag":tag, "uid":request.user.username},context_instance=RequestContext(request))
    else:
        if not request.user.is_authenticated():
            return render_to_response("stock.html", context_instance=RequestContext(request))
        else:
            return render_to_response("stock.html", {"uid":request.user.username},context_instance=RequestContext(request))
    
    #return HttpResponseRedirect('/sstock/istock.html?stockid='+str(param))

def helloworld(request):
    cursor = connection.cursor()
    cursor.execute("select * from mytest")
    row=cursor.fetchall()
    s = u"你好 " + str(row[0][0])
    return HttpResponse(s)

def fetch_curr_stock_info(stock_id):
    try:
        proxy=WSDL.Proxy('http://webservice.webxml.com.cn/WebServices/ChinaStockWebService.asmx?wsdl')
        proxy.soapproxy.config.buildWithNamespacePrefix = 0

        for i in proxy.methods:
            proxy.methods[i].namespace = proxy.wsdl.targetNamespace

        result  = proxy.getStockInfoByCode(theStockCode=stock_id)
        return result[0]
    except:
        return None

def fetch_curr_stock_chart(stock_id):
    try:
        proxy=WSDL.Proxy('http://webservice.webxml.com.cn/WebServices/ChinaStockWebService.asmx?wsdl')
        proxy.soapproxy.config.buildWithNamespacePrefix = 0

        for i in proxy.methods:
            proxy.methods[i].namespace = proxy.wsdl.targetNamespace

        result  = proxy.getStockImageByteByCode(theStockCode=stock_id)
        return result
    except:
        return None



def fetch_stock_kchart(stock_id, chart_type):
    try:
        proxy=WSDL.Proxy('http://webservice.webxml.com.cn/WebServices/ChinaStockWebService.asmx?wsdl')
        proxy.soapproxy.config.buildWithNamespacePrefix = 0

        for i in proxy.methods:
            proxy.methods[i].namespace = proxy.wsdl.targetNamespace

        result  = proxy.getStockImage_kByteByCode(theStockCode=stock_id, theType=chart_type)
        return result
    except:
        return None

def fetch_curr_stock_chart_from_ws(request):
    if request.method == 'GET':
        stock_id = request.GET['stockid']

        result = fetch_curr_stock_chart(stock_id)
        
        html = "<img src='data:image/gif;base64, "
        html += str(result)
        html += "'/>"
        return HttpResponse(html)

def fetch_curr_stock_kchart_from_ws(request):
    if request.method == 'GET':
        stock_id = request.GET['stockid']
        chart_type = request.GET['charttype']

        result = fetch_stock_kchart(stock_id, chart_type)
        
        html = "<img src='data:image/gif;base64, "
        html += str(result)
        html += "'/>"
        return HttpResponse(html)

class info:
    openp=0
    closep=0
    highp=0
    lowp =0
    vol  =0
    volumn=0
    change1=0
    change2=""
    lastestp=0
    
    stockid=""
    stockname=""
    datetime=""

    
def fetch_curr_stock_status_from_ws(request):
    """
    proxy=WSDL.Proxy('http://webservice.webxml.com.cn/WebServices/ChinaStockWebService.asmx?wsdl')
    proxy.soapproxy.config.buildWithNamespacePrefix = 0

    for i in proxy.methods:
        proxy.methods[i].namespace = proxy.wsdl.targetNamespace

    result = proxy.getStockImage_kByteByCode(theStockCode='sh600010', theType='D')
    html = "<html><body><img src='data:image/gif;base64, "
    html += str(result)
    html += "'/></body></html>"
    #result  = proxy.getStockInfoByCode(theStockCode='sh600010')
    """
    if request.method == 'GET':
        stock_id = request.GET['stockid']

        result = fetch_curr_stock_info(stock_id)
        #html = str(result)

        sinfo = info()
        sinfo.stockid = stock_id
        sinfo.stockname = result[1]
        sinfo.datetime  = result[2]
        sinfo.lastestp  = float(result[3])
        sinfo.closep    = float(result[4])
        sinfo.openp     = float(result[5])
        sinfo.change1   = float(result[6])
        sinfo.lowp      = float(result[7])
        sinfo.highp     = float(result[8])
        sinfo.change2   = result[9]
        sinfo.volumn    = float(result[10])
        sinfo.vol       = float(result[11])

        if sinfo.change1 > 0:
            sinfo.color="#800000"
        elif sinfo.change1 < 0:
            sinfo.color="#008000"
        else:
            sinfo.color="#000000"
        return render_to_response("status.html", {"info":sinfo})
    

def fetch_stock_deal_info_detail_by_datetime(stock_id, start_datetime, end_datetime):
    cursor = connection.cursor()
    cursor.execute("select NUM_DEALS, NUM_TRANSACTIONS, DEAL_TYPE, PRICE, DATETIME from STOCK_DEALING_INFO where STOCK_ID= '"+stock_id +"' and DATETIME >= '" + start_datetime + "' and DATETIME <= '" + end_datetime+"' ORDER BY DATETIME")
    rows = cursor.fetchall()

    li = []
    
    for row in rows:
        dl = DEAL_INFO()
        dl.num_deals = int(row[0])
        dl.num_transactions = int(row[1])
        dl.deal_type = int(row[2])
        dl.price = float(row[3])
        dl.datetime = str(row[4])
        li.append(dl)

    return li
        

def dealing_detail_data(stock_id, start_datetime, end_datetime, step_min=10):
    li = fetch_stock_deal_info_detail_by_datetime(stock_id, start_datetime, end_datetime)
    
    datetime_curr = datetime.datetime(int(start_datetime[0:4]), int(start_datetime[4:6]), int(start_datetime[6:8]), int(start_datetime[8:10]), int(start_datetime[10:12]), 0)
    datetime_end = datetime.datetime(int(end_datetime[0:4]), int(end_datetime[4:6]), int(end_datetime[6:8]), int(end_datetime[8:10]), int(end_datetime[10:12]), 0)

    dmin = datetime.timedelta(0, 60)
    dsmin = datetime.timedelta(0, step_min*60)
    
    chart_labels = []
    chart_values_buy = []
    chart_values_sell = []
    chart_values_unknown = []

    maxv = 0
    minv = 100000
    i = 0
    sd_curr = ""
    
    while datetime_curr <= datetime_end and i < len(li):
        
        if datetime_curr.weekday() == 0 or datetime_curr.weekday() == 6:
            datetime_curr += datetime.timedelta(0, 3600*24)
            continue
            
        if datetime_curr.time() < datetime.time(9, 30, 0):
            datetime_curr = datetime.datetime(datetime_curr.year, datetime_curr.month, datetime_curr.day, 9, 30, 0)
        
        if datetime_curr.time() > datetime.time(11, 30, 0) and datetime_curr.time() < datetime.time(13, 0, 0):
            datetime_curr = datetime.datetime(datetime_curr.year, datetime_curr.month, datetime_curr.day, 13, 0, 0)

        if datetime_curr.time() > datetime.time(15, 0, 0):
            datetime_curr += datetime.timedelta(0, 3600*24)
            datetime_curr = datetime.datetime(datetime_curr.year, datetime_curr.month, datetime_curr.day, 9, 30, 0)
            continue
        
        datetime_next = datetime_curr + dsmin
        
        #s = li[i].datetime
        v1 = 0
        v2 = 0
            
        #s = "%04d%02d%02d%02d%02d%02d" % (datetime_curr.year, datetime_curr.month, datetime_curr.day, datetime_curr.hour, datetime_curr.minute, datetime_curr.second)
        sd_next = "%04d%02d%02d%02d%02d%02d" % (datetime_next.year, datetime_next.month, datetime_next.day, datetime_next.hour, datetime_next.minute, datetime_next.second)
        sd_curr = "%04d%02d%02d%02d%02d%02d" % (datetime_curr.year, datetime_curr.month, datetime_curr.day, datetime_curr.hour, datetime_curr.minute, datetime_curr.second)
        
        while i < len(li) and li[i].datetime < sd_next and li[i].datetime >= sd_curr:
            if li[i].deal_type == 0:
                v1 += li[i].num_deals
            else:
                v2 += li[i].num_deals
            i += 1
        if datetime_curr.time() == datetime.time(9, 30, 0):
            s = "%04d%02d%02d %02d:%02d" % (datetime_curr.year, datetime_curr.month, datetime_curr.day, datetime_curr.hour, datetime_curr.minute)
        else:
            s = "%02d:%02d" % (datetime_curr.hour, datetime_curr.minute)
            
        chart_values_buy.append(v1)
        chart_values_sell.append(v2)
        chart_labels.append(s)

        if v1 > maxv:
            maxv = v1
        if v2 > maxv:
            maxv = v2

        datetime_curr = datetime_next
    
    return (chart_values_buy, chart_values_sell, chart_values_unknown, maxv, chart_labels)

def deal_type_data(stock_id, start_datetime, end_datetime):
    li = fetch_stock_deal_info_detail_by_datetime(stock_id, start_datetime, end_datetime)

    deal_type = [0, 0, 0, 0]

    for i in li:
        deal_per_trans = i.num_deals / i.num_transactions

        v = 0
        if i.deal_type == 0:
            v = 1
        elif i.deal_type == 1:
            v = -1
        
        if deal_per_trans >= 1000:
            deal_type[3] += v*i.num_deals
        elif deal_per_trans >= 500:
            deal_type[2] += v*i.num_deals
        elif deal_per_trans >= 100:
            deal_type[1] += v*i.num_deals
        else:
            deal_type[0] += v*i.num_deals

    return deal_type

def deal_type_piechart(request):
    if request.method == 'GET':
        param = request.GET['param']
        pli = param.split('@')

        start_datetime = pli[0]
        end_datetime = pli[1]
        stock_id = pli[2]

        deal_type = deal_type_data(stock_id, start_datetime, end_datetime)

        for i in range(0, 4):
            deal_type[i] = abs(deal_type[i])
        
        json_data = '{"elements": [{"colours": ["#ff0000", "#00ff00", "#0000ff", "#ff00ff"], "border":2, "gradient-fill":true, "alpha": 0.59999999999999998, "type": "pie", "values": [{"value":'+str(deal_type[0])+', "label" : "小单", "animate":[{"type":"bounce","distance":20}]}, {"value":'+str(deal_type[1])+', "label" : "中单", "animate":[{"type":"bounce","distance":20}]}, {"value":'+str(deal_type[2])+', "label" : "大单", "animate":[{"type":"bounce","distance":20}]}, {"value":'+str(deal_type[3])+', "label" : "特大单", "animate":[{"type":"bounce","distance":20}]}]}]}'
        
        return HttpResponse(json_data)

def deal_type_chart(request):
    if request.method == 'GET':
        param = request.GET['param']
        pli = param.split('@')
        
        start_datetime = pli[0]
        end_datetime = pli[1]
        stock_id = pli[2]

        deal_type = deal_type_data(stock_id, start_datetime, end_datetime)

        bar_on_show1 = bar_on_show(type='grow-up', cascade=1)
        #bar_on_show2 = bar_on_show(type='grow-up', cascade=1, delay=2)
        #bar_on_show3 = bar_on_show(type='grow-up', cascade=1, delay=3)
        #bar_on_show4 = bar_on_show(type='grow-up', cascade=1, delay=4)

        maxv = math.ceil(abs(max(deal_type, key=abs)) * 1.2)
        minv = -maxv
        
        bv = []
        for i in range(0, 4):
            if deal_type[i] > 0:
                bv.append(barvalue(top=deal_type[i], colour='#ff0000'))
            else:
                bv.append(barvalue(top=deal_type[i], colour='#00ff00'))

        b1 = bar_glass(on_show=bar_on_show1, values=bv)
        #b2 = bar_glass(on_show=bar_on_show2)
        #b3 = bar_glass(on_show=bar_on_show3)
        #b4 = bar_glass(on_show=bar_on_show4)
        
        step = math.ceil((maxv-minv) / 10.0)

        xs = x_axis(labels = {"labels":[u'\u5c0f\u5355', u'\u4e2d\u5355', u'\u5927\u5355', u'\u7279\u5927\u5355']})
        ys = y_axis(max=maxv, min=minv, steps=step)
        chart = open_flash_chart(x_axis=xs, y_axis=ys)

        #b1.values = deal_type
        #b2.values = [deal_type[1]]
        #b3.values = [deal_type[2]]
        #b4.values = [deal_type[3]]

        chart.add_element(b1)
        #chart.add_element(b2)
        #chart.add_element(b3)
        #chart.add_element(b4)

        return HttpResponse(chart.render())
        
def deal_buyandsell_data(request):
    if request.method == 'GET':
        param = request.GET['param']
        pli = param.split('@')
        
        start_datetime = pli[0]
        end_datetime = pli[1]
        stock_id = pli[2]

        chart = open_flash_chart()

        rtuple = dealing_detail_data(stock_id, start_datetime, end_datetime)
            
        chart_values_buy = rtuple[0]
        chart_values_sell = rtuple[1]
        maxv = rtuple[3]
        minv = 0

        p1 = pie()
        p1.alpha = 0.6
        
        p1.colours = ["#ff0000", "#00ff00"]
        p1.values = [sum(chart_values_buy), sum(chart_values_sell)]

        chart.add_element(p1)
        #json_data = '{"elements": [{"colours": ["#ff0000", "#00ff00", "#0000ff", "#ff00ff"], "border":2, "gradient-fill":true, "alpha": 0.59999999999999998, "type": "pie", "values": [{"value":'+str(20)+', "label" : "买入", "animate":[{"type":"bounce","distance":20}]}, {"value":'+str(10)+', "label" : "卖出", "animate":[{"type":"bounce","distance":20}]}]}]}'
        json_data = '{"elements": [{"colours": ["#ff0000", "#00ff00"],"border":2,"gradient-fill" :  true, "alpha": 0.59999999999999998, "type": "pie", "values": [{"value":'+str(p1.values[0])+', "label" : "买入", "animate":[{"type":"bounce","distance":20}]}, {"value":'+str(p1.values[1])+', "label" : "卖出", "animate":[{"type":"bounce","distance":20}]}]}]}'

        return HttpResponse(json_data)

def deal_detail_chart_data_min(request):
    if request.method == 'GET':
        param = request.GET['param']
        pli = param.split('@')
        
        start_datetime = pli[0]
        end_datetime = pli[1]
        stock_id = pli[2]

        chart = open_flash_chart()

        rtuple = dealing_detail_data(stock_id, start_datetime, end_datetime)
            
        chart_values_buy = rtuple[0]
        chart_values_sell = rtuple[1]
        
        maxv = rtuple[3]
        minv = 0
        chart_labels  = rtuple[4]
        
        bar_on_show1 = bar_on_show(type='grow-up', cascade=1)
        bar_on_show2 = bar_on_show(type='grow-up', cascade=1, delay=2)

        b1 = bar_glass(on_show=bar_on_show1)
        b2 = bar_glass(on_show=bar_on_show2)
        
        maxv = math.ceil(1.2*maxv)
        step = math.ceil((maxv-minv) / 10.0)
        
        ys = y_axis(max=maxv, min=0, steps=step)

        label_steps = 1#max(len(chart_values_buy)/5, len(chart_values_sell)/5, 1)
        xs_l = x_axis_labels(steps = label_steps, labels=chart_labels, rotate='vertical')

        chart = open_flash_chart(y_axis=ys, x_axis=x_axis(labels=xs_l))
        
        b1.values = chart_values_buy
        b1.colour = "#ff0000"

        b2.values = chart_values_sell
        b2.colour = "#00ff00"
        
        chart.add_element(b1)
        chart.add_element(b2)
        
        return HttpResponse(chart.render())
        #return HttpResponse(str(rtuple[5]) + " "  + str(rtuple[6]) + " " + str(rtuple[7]))
        
    
def chart_data(request):
    t = title(text=time.strftime('%a %Y %b %d'))
    b1 = bar()
    b1.values = range(9,0,-1)
    b2 = bar(on_show=bar_on_show(type='pop'))

    b2.values = [random.randint(0,9) for i in range(9)]
    b2.colour = '#56acde'
    chart = open_flash_chart()
    chart.title = t

    p1 = pie()
    p1.values = [0.3, 0.7]
    p1.alpha = 0.2
    p1.colours = ["#ff0000", "#00ff00"]

    chart.add_element(p1)
    #chart.add_element(b1)
    #chart.add_element(b2)
    return HttpResponse(chart.render())

def test(request):
    
    if not request.user.is_authenticated():
        #return render_to_response("stock_main.html", {})
        return render_to_response("stock_main.html", context_instance=RequestContext(request))
    else:
        return render_to_response("stock_main.html", {"uid":request.user.username}, context_instance=RequestContext(request))
    

def index(request):
    c = {}
    c.update(csrf(request))
    
    #t = get_template('index.html')
    #html = t.render(Context())
    
    return render_to_response("index.html", c)

def register(request):
    #c = {}
    #c.update(csrf(request))
    
    if request.method == 'POST':
        try:
            uid = request.POST['usrid']
            passwd = request.POST['passwd']
            confirm_passwd = request.POST['confirmpasswd']
            email_addr = request.POST['email']

            if confirm_passwd == passwd:
                new_user = User.objects.create_user(username=uid, password=passwd, email=email_addr)
                return HttpResponse(new_user)

            return HttpResponse("error1")
        except Exception, Ex:
            return HttpResponse(Ex)
    else:
        form = UserCreationForm()
    return render_to_response("register.html", context_instance=RequestContext(request))

def login(request):
    if request.method == 'POST':
        uid = request.POST['usrid']
        passwd = request.POST['passwd']
        staylogin = None
        if request.POST.has_key('staylogin'):
            staylogin = request.POST['staylogin']
            
        user = auth.authenticate(username = uid, password=passwd)
        
        if user is not None and user.is_active:
            if not staylogin:
                request.session.set_expiry(0)
            else:
                request.session.set_expiry(None)
            auth.login(request, user)
            
            return HttpResponseRedirect("/istock/test/")
        else:
            return HttpResponse("failed")
    
    return render_to_response("login.html", context_instance=RequestContext(request))

def logout(request):
    auth.logout(request)
    
    return HttpResponseRedirect("/istock/test/")
